package reqUpload;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

@WebServlet(value = "/reqUpload/demo02")
@MultipartConfig
public class requestUploadDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Allow-Origin", "*");
        Collection<Part> files = request.getParts();
        String uploadPath = request.getServletContext().getRealPath("/reqUploads2");
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        files.forEach(part -> {
            String fileName = part.getSubmittedFileName();
            String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
            try {
                part.write(uploadPath+"/"+newFileName);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        String respString = files.stream().map(part -> part.getSubmittedFileName())
                .collect(Collectors.joining(","));
        response.setContentType("text/plain; charset=UTF-8");
        response.getWriter().write(respString+"  文件上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
